/*
 * Copyright 2008 Carnegie Mellon University
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package edu.cmu.lti.sepia.infra.run;

import java.util.List;

import edu.cmu.lti.sepia.infra.run.model.AnswerType;
import edu.cmu.lti.sepia.infra.run.model.QuestionAnalysisResult;
import edu.cmu.lti.sepia.infra.run.model.QuestionAnalysisResultSet;
import edu.cmu.lti.sepia.infra.run.model.Term;
import edu.cmu.lti.sepia.util.FormatUtil;

public class QuestionAnalysisObjToXml {

  public static String serialize( QuestionAnalysisResultSet resultSet ) {
    StringBuilder sb = new StringBuilder();
    sb.append("<TOPIC_SET>\n");
    if (resultSet.getMetadata().size()>0) {
      sb.append("  <METADATA>");
      for ( String key : resultSet.getMetadata().keySet() ) {
        sb.append("  <"+key+">"+resultSet.getMetadata().get(key)+"</"+key+">");
      }
      sb.append("  </METADATA>");
    }
    
    for ( String topicId : resultSet.keySet() ) {
      QuestionAnalysisResult result = resultSet.get(topicId);
      sb.append("  <TOPIC ID=\""+topicId+"\">\n");
      sb.append("    <QUESTION_ANALYSIS>\n");
      AnswerType atype = result.getAnswerType();
      if (atype!=null) {
        sb.append("      <ANSWERTYPE SCORE=\""+FormatUtil.nf3(atype.getScore())+"\">"+atype.getText()+"</ANSWERTYPE>\n");
      }
      List<Term> terms = result.getKeyterms();
      if (terms!=null && terms.size()>0) {
        String lang = resultSet.getTargetLanguage();
        sb.append("      <KEYTERMS" );
        sb.append( lang !=null ? (" LANGUAGE=\"" +resultSet.getTargetLanguage()+"\""):"" );
        sb.append(">\n");
        for ( Term t : terms ) {
          sb.append("        <KEYTERM SCORE=\""+FormatUtil.nf3(t.getScore())+"\">");
          sb.append("<![CDATA["+ t.getText() +"]]>");
          sb.append("</KEYTERM>\n");
        }
        sb.append("      </KEYTERMS>\n");
      }
      sb.append("    </QUESTION_ANALYSIS>\n");
      sb.append("  </TOPIC>\n");
    }
    sb.append("</TOPIC_SET>\n");
    
    return sb.toString();
  }
  
}
